package com.hdd.utils.wx.pay;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PayContoller {

    /**
     * 企业付款到用户个人微信
     * 简单demo 需要自行完善逻辑
     * @return
     */
    @RequestMapping(value = "/transfers")
    public String transfers() throws Exception{

        File pkcFile = ResourceUtils.getFile("classpath:apiclient_cert.p12");
        String orderNo = System.currentTimeMillis()+"";//订单编号 可以参考：https://www.cnblogs.com/pxblog/p/12818067.html
        String weixinOpenId = "orCqD4lyeBSfosShi7OaT5MQPH7Q";//用户的openid 可以参考：https://www.cnblogs.com/pxblog/p/10542698.html";
        String realname = "方泽华";
        //转账的金额  金额格式转换可以参考 https://www.cnblogs.com/pxblog/p/13186037.html
        Double payAmount = 1.00;
        String desc = "画多多提现";
        String ip = "127.0.0.1";//ip地址 可以参考：https://www.cnblogs.com/pxblog/p/13360768.html

        Object result[] = WeixinPay.payToUser(pkcFile, orderNo, weixinOpenId, realname, payAmount, desc, ip);
        String resXml = (String) result[1];
        boolean postError = (Boolean) result[0];
        if (!postError) {
            Map<String, String> map = new HashMap<String, String>();
            try {
                map = PayUtil.parseXMLToMap(resXml);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String returnCode = map.get("return_code");
            if (returnCode.equalsIgnoreCase("FAIL")) {
                //支付失败
                return map.get("return_msg");
            } else if (returnCode.equalsIgnoreCase("SUCCESS")) {
                if (map.get("err_code") != null) {
                    //支付失败
                    return map.get("err_code_des");
                } else if (map.get("result_code").equalsIgnoreCase(
                        "SUCCESS")) {
                    //支付成功  paymentNo：微信付款单号  payment_time：付款成功时间
                    String paymentNo = map.get("payment_no");
                    String paymentTradeNo = map.get("partner_trade_no");
                    String payment_time = map.get("payment_time");
                    try {
                        //如果是体现操作，在这里处理体现订单的状态，把状态转为提现成功

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return "返回到成功的页面";
                }
            }
        }

        return "返回通信失败的错误页面";
    }
}